package com.jihox.abookpro;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Vector;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextPaint;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jihox.abookpro.R;
import com.jihox.abookpro.alipay.JHAlipay;
import com.jihox.abookpro.alipay.Keys;
import com.jihox.abookpro.alipay.Result;
import com.jihox.abookpro.alipay.Rsa;
import com.jihox.abookpro.dao.BookProjectDAO;
import com.jihox.abookpro.dao.OrderDAO;
import com.jihox.abookpro.domain.Order;
import com.jihox.abookpro.helper.MailSendHelp;
import com.jihox.abookpro.helper.UserHelper;
import com.jihox.abookpro.util.ConfigProperties;
import com.jihox.abookpro.util.FileUtil;
import com.jihox.abookpro.util.MailSenderInfo;
import com.jihox.abookpro.util.NetStatus;
import com.jihox.abookpro.view.BorderTextView;
import com.jihox.abookpro.view.JHProgressDialog;

public class PayActivity extends BaseActivity {

	private static final int RQF_PAY = 1;
	private static final int RQF_LOGIN = 2;
	public static final String TAG = "alipay-sdk";
	private String orderCode = "";

	private String shippingfee = "";

	private String total_fee = "";
	private float total_fee_with_discount=0;
	private boolean useCode = false;
	private Order orderInfo = null;
	
	private CheckBox is_discount_checkbox;
	private RelativeLayout discount_code_area;
	private EditText discount_code_edittext;
	private TextView discount_num;
	private final int capacity = 10;
	private ProgressBar discount_code_progressbar;
	private ImageView discount_code_Success_img;
	private ImageView discount_code_Fail_img;
	private TextView real_pay_num;
	private Vector<BorderTextView> codes;
	private RelativeLayout checkbox_layout;
	private static final int REQUEST_TIMEOUT = 10*1000;//设置请求超时10秒钟  
	private static final int SO_TIMEOUT = 10*1000;  //设置等待数据超时时间10秒钟  
	private static final int SUCCESS = 1;
	private static final int FAIL = 2;
	private static final int LOADING = 3;
	private static final int NONE = 0;
	private Button payButton;
	private Button quickPayButton;
	private JHProgressDialog pd;
	private static final String password = "MGECAQACEQClbRr+HCcUiEovdVPE3SstAgMBAAECEGCIvsuy2gtcXJKySicg03ECCQDYZQ2pLemYewIJAMOz+YiFlL53AghtyK7qkul9OwIIeo90v8YAgEMCCF2nkEE3";
	private String alipaynotifyurl ="";
	
	private String from = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pay);
		checkbox_layout = (RelativeLayout) findViewById(R.id.checkbox_layout);
		discount_code_progressbar = (ProgressBar) findViewById(R.id.discount_code_progressbar);
		discount_code_Success_img = (ImageView) findViewById(R.id.discount_code_Success_img);
		discount_code_Fail_img = (ImageView) findViewById(R.id.discount_code_Fail_img);
		discount_num = (TextView) findViewById(R.id.discount_num);
		discount_code_edittext = (EditText) findViewById(R.id.discount_code_edittext);
		real_pay_num = (TextView) findViewById(R.id.real_pay_num);
		quickPayButton = (Button) findViewById(R.id.btnQuickPay);
		
		updateGetDiscountStatus(NONE);
		initCodes();

		discount_code_edittext.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showInputMethod(discount_code_edittext,true);
				discount_code_edittext.setSelection(discount_code_edittext.getText().length());
			}
		}); 

		discount_code_edittext.setFilters(new InputFilter[]{new InputFilter.LengthFilter(capacity)}); 
		discount_code_edittext.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				updateCodes();
				if(discount_code_edittext.getText().length()==capacity){
					discount_code_edittext.setEnabled(false);
					showInputMethod(discount_code_edittext, false);
					updateGetDiscountStatus(LOADING);
					new Thread(getPreferentialRunnable).start();
				}
			}
		});
		discount_code_area = (RelativeLayout) findViewById(R.id.discount_code_area);

		is_discount_checkbox = (CheckBox) findViewById(R.id.is_discount_checkbox);
		is_discount_checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked){
					discount_code_area.setVisibility(View.VISIBLE);
					discount_code_edittext.setSelected(true);
					showInputMethod(discount_code_edittext,true);
					updateGetDiscountStatus(NONE);
				}else{
					discount_code_edittext.setText("");
					discount_code_edittext.setSelected(false);
					showInputMethod(discount_code_edittext,false);
					discount_code_area.setVisibility(View.GONE);
					updateGetDiscountStatus(NONE);
					real_pay_num.setText(getResources().getString(R.string.RealNeedToPay)+total_fee + getResources().getString(R.string.T_Price_uint));
					payButton.setVisibility(View.VISIBLE);
					quickPayButton.setVisibility(View.GONE);

				}
			}
		});
		checkbox_layout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				is_discount_checkbox.setChecked(is_discount_checkbox.isChecked()?false:true);
				if(is_discount_checkbox.isChecked()){
					showInputMethod(discount_code_edittext,true);
					updateGetDiscountStatus(NONE);
					discount_code_edittext.setSelection(discount_code_edittext.getText().length());
				}else{
					showInputMethod(discount_code_edittext,false);
					updateGetDiscountStatus(NONE);
					real_pay_num.setText(getResources().getString(R.string.RealNeedToPay)+total_fee + getResources().getString(R.string.T_Price_uint));
					payButton.setVisibility(View.VISIBLE);
					quickPayButton.setVisibility(View.GONE);
				}
			}
		});

		Intent intent = this.getIntent();
		Bundle bundle = intent.getExtras();
		from = bundle.getString("From",null);
		orderInfo = (Order)bundle.getSerializable("OrderInfo");
	
		orderCode = orderInfo.getOrderId();
		shippingfee = String.valueOf(orderInfo.getShippingfee());
		String quantity = orderInfo.getNumber();
		String orderDeliveryCycle = orderInfo.getOrderDeliveryCycle();
		
		float price = orderInfo.getPrice();
		TextView txtQuantity = (TextView) findViewById(R.id.tvQuantity);
		txtQuantity.setText(quantity + "×"
				+ orderInfo.getBookProject().getBook().getProduct().getName());

		DecimalFormat df = new DecimalFormat();
		df.setMaximumFractionDigits(2);
		String amount = df.format(price
				* Integer.valueOf(quantity));
		TextView txtAmount = (TextView) findViewById(R.id.tvAmount);
		txtAmount.setText(amount + getResources().getString(R.string.T_Price_uint));

		TextView txtShippingfee = (TextView) findViewById(R.id.tvShippingfee);
		txtShippingfee.setText(shippingfee + getResources().getString(R.string.T_Price_uint));

		TextView txtSum = (TextView) findViewById(R.id.tvSum);
		total_fee = String.valueOf(Float.valueOf(amount) + Float.valueOf(shippingfee));
		txtSum.setText(total_fee + getResources().getString(R.string.T_Price_uint));
		real_pay_num.setText(getResources().getString(R.string.RealNeedToPay)+total_fee + getResources().getString(R.string.T_Price_uint));
		TextPaint tp = txtSum.getPaint();
		tp.setFakeBoldText(true);

		TextView txtSumLable = (TextView) findViewById(R.id.tvSumLable);
		tp = txtSumLable.getPaint();
		tp.setFakeBoldText(true);

		SimpleDateFormat formatter =new SimpleDateFormat (getResources().getString(R.string.TimeFormat));  
		Calendar cal = Calendar.getInstance();
		if (orderDeliveryCycle == null || orderDeliveryCycle.isEmpty()){
			orderDeliveryCycle ="10";
		}

		cal.add(Calendar.DAY_OF_MONTH, Integer.valueOf(orderDeliveryCycle));

		//获取当前时间    
		String str = formatter.format(cal.getTime());  
		TextView deliver_date=  (TextView) findViewById(R.id.deliver_date);
		deliver_date.setText(getResources().getString(R.string.X_Order_Send_Time) + ": "+ str);

		Button returnButton = (Button) findViewById(R.id.btnReturn);
		payButton = (Button) findViewById(R.id.btnPay);
		returnButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				showDialog();
			}
		});

		quickPayButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				quickPayButton.setEnabled(false);
				pd = JHProgressDialog.show(PayActivity.this, null,
						getResources().getString(R.string.Paying));
				new Thread(quickPayRunnable).start();

			}
		});
		payButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				payButton.setEnabled(false);
				
				if(useCode){
					pd = JHProgressDialog.show(PayActivity.this, null,
							getResources().getString(R.string.Paying));
					new Thread(mixPayRunnable).start();
				}else{
					aliPay();
				}
			}
		});
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					File file = new File(getFilesDir(),orderInfo.getOrderId() + "_" + orderInfo.getWorksn()
							+ "_original.zip");
					
					orderInfo.setZipFilePath(file.toString());
					OrderDAO orderDao = new OrderDAO(PayActivity.this);	
					orderDao.updateOrderFilePath(orderInfo.getOrderId(), orderInfo.getZipFilePath());
					Log.d("PayActivity","ZipFilePath = " + file.toString());
					BookProjectDAO dao = new BookProjectDAO();
					dao.saveAndZip(orderInfo.getBookProject(), file,new File(getCacheDir(),orderInfo.getOrderId()).getPath());
					orderInfo.setZipFileCrc(FileUtil.getCRC32(file.toString()));
					orderInfo.setZipFileSize(file.length());

					orderDao.updateOrderFileCrc(orderInfo);
				} catch (Exception e) {
					MyUncaughtExceptionHandler.getInstance().SendExceptionByEmail(e, "package error");
					e.printStackTrace();
				}
			}

		}).start();
	}
	
	private void aliPay(){
		try {
			if (NetStatus.getNetState(getApplicationContext()) == NetStatus.NET_NOT_PREPARE) {
				showToast( getResources().getString(R.string.T_Pay_Fail_Net));
				payButton.setEnabled(true);
				return;
			}
			
			pd = JHProgressDialog.show(PayActivity.this, null,
					getResources().getString(R.string.T_Loading_short));
			new Thread(getAlipayconfigsRunnable).start();

		} catch (Exception ex) {
			ex.printStackTrace();
			if (useCode){
				cancelCoupon();
			}else{
				showToast(getResources().getString(R.string.T_Pay_Fail));
			}
			
			payButton.setEnabled(true);
		}
	}

	private void updateGetDiscountStatus(int status){
		switch (status) {
		case SUCCESS:
			discount_code_progressbar.setVisibility(View.INVISIBLE);
			discount_code_Success_img.setVisibility(View.VISIBLE);
			discount_code_Fail_img.setVisibility(View.INVISIBLE);
			discount_num.setVisibility(View.VISIBLE);
			useCode = true;
			break;
		case FAIL:
			discount_code_progressbar.setVisibility(View.INVISIBLE);
			discount_code_Success_img.setVisibility(View.INVISIBLE);
			discount_code_Fail_img.setVisibility(View.VISIBLE);
			discount_num.setVisibility(View.INVISIBLE);
			discount_code_edittext.setEnabled(true);
			useCode = false;
			break;
		case LOADING:
			discount_code_progressbar.setVisibility(View.VISIBLE);
			discount_code_Success_img.setVisibility(View.INVISIBLE);
			discount_code_Fail_img.setVisibility(View.INVISIBLE);
			discount_num.setVisibility(View.INVISIBLE);
			break;
		case NONE:
			discount_code_progressbar.setVisibility(View.INVISIBLE);
			discount_code_Success_img.setVisibility(View.INVISIBLE);
			discount_code_Fail_img.setVisibility(View.INVISIBLE);
			discount_num.setVisibility(View.INVISIBLE);
			discount_code_edittext.setEnabled(true);
			discount_code_edittext.requestFocus();
			useCode = false;
			break;
		default:
			discount_code_progressbar.setVisibility(View.INVISIBLE);
			discount_code_Success_img.setVisibility(View.INVISIBLE);
			discount_code_Fail_img.setVisibility(View.INVISIBLE);
			discount_num.setVisibility(View.INVISIBLE);
			discount_code_edittext.setEnabled(true);
			useCode = false;
			break;
		}
	}

	Runnable getPreferentialRunnable = new Runnable() {
		@Override
		public void run() {
			BasicHttpParams httpParams = new BasicHttpParams();  
			HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);  
			HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);  
			List <NameValuePair> params = new ArrayList<NameValuePair>();  
			params.add(new BasicNameValuePair("order_id", orderCode));
			params.add(new BasicNameValuePair("coupon_code", discount_code_edittext.getText().toString())); 

			HttpClient httpclient = new DefaultHttpClient(httpParams);
			HttpPost httpPost = new HttpPost(
					ConfigProperties.getPreferential());
			UserHelper helper = new UserHelper();
			httpPost.setHeader("username", helper.getUserName());
			httpPost.setHeader("password", helper.getPassword());

			Message msg = new Message();
			Bundle data = new Bundle();
			try {
				httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
				HttpResponse response = httpclient.execute(httpPost);
				HttpEntity resEntity = response.getEntity();

				if (resEntity != null) {

					String res = EntityUtils.toString(resEntity, Charset
							.forName("UTF-8").toString());
					data.putString("value", res);
					resEntity.consumeContent();
				}

			} catch (UnsupportedEncodingException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet_NoPreferential));
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet_NoPreferential));
				e.printStackTrace();
			} catch (IOException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet_NoPreferential));
				e.printStackTrace();
			} catch (ParseException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet_NoPreferential));
				e.printStackTrace();
			} catch (Exception e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet_NoPreferential));
				e.printStackTrace();
			} finally {
				msg.setData(data);
				preferentialHandler.sendMessage(msg);
				httpclient.getConnectionManager().shutdown();
			}
		}
	};

	Runnable quickPayRunnable = new Runnable() {
		@Override
		public void run() {
			BasicHttpParams httpParams = new BasicHttpParams();  
			HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);  
			HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);  
			List <NameValuePair> params = new ArrayList<NameValuePair>();  
			params.add(new BasicNameValuePair("order_id", orderCode));
			params.add(new BasicNameValuePair("couponids", discount_code_edittext.getText().toString()));
			HttpClient httpclient = new DefaultHttpClient(httpParams);
			HttpPost httpPost = new HttpPost(
					ConfigProperties.getQuickpay());
			UserHelper helper = new UserHelper();
			httpPost.setHeader("username", helper.getUserName());
			httpPost.setHeader("password", helper.getPassword());

			Message msg = new Message();
			Bundle data = new Bundle();
			try {
				httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
				HttpResponse response = httpclient.execute(httpPost);
				HttpEntity resEntity = response.getEntity();

				if (resEntity != null) {

					String res = EntityUtils.toString(resEntity, Charset
							.forName("UTF-8").toString());
					data.putString("value", res);
					resEntity.consumeContent();
				}

			} catch (UnsupportedEncodingException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet_NoPreferential));
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet_NoPreferential));
				e.printStackTrace();
			} catch (IOException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet_NoPreferential));
				e.printStackTrace();
			} catch (ParseException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet_NoPreferential));
				e.printStackTrace();
			} catch (Exception e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet_NoPreferential));
				e.printStackTrace();
			} finally {
				msg.setData(data);
				quickPayHandler.sendMessage(msg);
				httpclient.getConnectionManager().shutdown();
			}
		}
	};
	
	Runnable mixPayRunnable = new Runnable() {
		@Override
		public void run() {
			BasicHttpParams httpParams = new BasicHttpParams();  
			HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);  
			HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);  
			List <NameValuePair> params = new ArrayList<NameValuePair>();  
			params.add(new BasicNameValuePair("order_id", orderCode));
			params.add(new BasicNameValuePair("couponids", discount_code_edittext.getText().toString()));
			HttpClient httpclient = new DefaultHttpClient(httpParams);
			HttpPost httpPost = new HttpPost(
					ConfigProperties.getMixPay());
			UserHelper helper = new UserHelper();
			httpPost.setHeader("username", helper.getUserName());
			httpPost.setHeader("password", helper.getPassword());

			Message msg = new Message();
			Bundle data = new Bundle();
			try {
				httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
				HttpResponse response = httpclient.execute(httpPost);
				HttpEntity resEntity = response.getEntity();

				if (resEntity != null) {

					String res = EntityUtils.toString(resEntity, Charset
							.forName("UTF-8").toString());
			        data.putString("value", res);
					resEntity.consumeContent();
				}

			} catch (UnsupportedEncodingException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet_NoPreferentialForPay));
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet_NoPreferentialForPay));
				e.printStackTrace();
			} catch (IOException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet_NoPreferentialForPay));
				e.printStackTrace();
			} catch (ParseException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet_NoPreferentialForPay));
				e.printStackTrace();
			} catch (Exception e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet_NoPreferentialForPay));
				e.printStackTrace();
			} finally {
				msg.setData(data);
				mixPayHandler.sendMessage(msg);
				httpclient.getConnectionManager().shutdown();
			}
		}
	};
	
	private void cancelCoupon(){
		pd = JHProgressDialog.show(PayActivity.this, null,
				getResources().getString(R.string.T_CancelCoupon));
		new Thread(cancelCouponRunnable).start();
	}
	
	Runnable cancelCouponRunnable = new Runnable() {
		@Override
		public void run() {
			BasicHttpParams httpParams = new BasicHttpParams();  
			HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);  
			HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);  
			List <NameValuePair> params = new ArrayList<NameValuePair>();  
			params.add(new BasicNameValuePair("order_id", orderCode));
			params.add(new BasicNameValuePair("couponids", discount_code_edittext.getText().toString()));
			HttpClient httpclient = new DefaultHttpClient(httpParams);
			String url = ConfigProperties.getCancelCouponUrl();
			HttpPost httpPost = new HttpPost(url);
			UserHelper helper = new UserHelper();
			httpPost.setHeader("username", helper.getUserName());
			httpPost.setHeader("password", helper.getPassword());

			Message msg = new Message();
			Bundle data = new Bundle();
			try {
				httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
				HttpResponse response = httpclient.execute(httpPost);
				HttpEntity resEntity = response.getEntity();

				if (resEntity != null) {

					String res = EntityUtils.toString(resEntity, Charset
							.forName("UTF-8").toString());
			        data.putString("value", res);
					resEntity.consumeContent();
				}

			} catch (UnsupportedEncodingException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet_NoPreferentialForPay));
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet_NoPreferentialForPay));
				e.printStackTrace();
			} catch (IOException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet_NoPreferentialForPay));
				e.printStackTrace();
			} catch (ParseException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet_NoPreferentialForPay));
				e.printStackTrace();
			} catch (Exception e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet_NoPreferentialForPay));
				e.printStackTrace();
			} finally {
				msg.setData(data);
				cancelCouponHandler.sendMessage(msg);
				httpclient.getConnectionManager().shutdown();
			}
		}
	};

	Handler cancelCouponHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			pd.dismiss();

			Bundle data = msg.getData();
			String error = data.getString("Error");
			if (error != null && !error.isEmpty()) {
				dialog();
				payButton.setEnabled(true);
				return;
			}

			String val = data.getString("value");
		
			try {
				JSONObject result = new JSONObject(val);
				boolean isSuccess = result.getBoolean("success");
				if (!isSuccess){
					dialog();
				}else{
					Intent intent = new Intent();
					intent.setClass(PayActivity.this, PayFailedActivity.class);
					Bundle bundle = new Bundle();
					bundle.putSerializable("orderInfo", orderInfo);

					intent.putExtras(bundle);
					PayActivity.this.startActivity(intent);
					payButton.setEnabled(true);
				}
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				showToast(getResources().getString(R.string.T_NoNet_NoPreferential));
			} catch(Exception e){
				showToast(e.getMessage());
			}
		}
	};
	
	private void dialog() {

		final Dialog dialog = new Dialog(PayActivity.this, R.style.JHDialog);
        //设置它的ContentView
        dialog.setContentView(R.layout.dialog_general);
        Button buttonOK = (Button) dialog.findViewById(R.id.dialog_button_ok);
        Button buttonCancel = (Button) dialog.findViewById(R.id.dialog_button_cancel);
        TextView dialogTitle = (TextView) dialog.findViewById(R.id.dialog_title);
        TextView dialogMessage = (TextView) dialog.findViewById(R.id.dialog_message);
  
        buttonOK.setBackgroundResource(R.drawable.green_style);
        buttonOK.setText(R.string.T_Ok);
        dialogTitle.setText(getResources().getString(R.string.T_CancelCoupon_Failed));
        dialogMessage.setText(R.string.T_Retry);
        dialog.setCanceledOnTouchOutside(false);
        buttonOK.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				cancelCoupon();
				
			}
		});
        buttonCancel.setBackgroundResource(R.drawable.grey_style);
		buttonCancel.setText(R.string.T_Cancel);

		buttonCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
        dialog.show();
	}
	
	Handler mixPayHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			pd.dismiss();

			Bundle data = msg.getData();
			String error = data.getString("Error");
			if (error != null && !error.isEmpty()) {
				showToast(error);
				payButton.setEnabled(true);
				return;
			}
			int flag = FAIL;
			String val = data.getString("value");
			String quickPayMsg =null;
			try {
				JSONObject result = new JSONObject(val);
				boolean isSuccess = result.getBoolean("success");
				if (!isSuccess){
					quickPayMsg = result.getString("msg");
				}
				flag = isSuccess?SUCCESS:FAIL;
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				showToast(getResources().getString(R.string.T_NoNet_NoPreferential));
			} catch(Exception e){
				showToast(e.getMessage());
			}

			switch (flag) {
			case SUCCESS:
				aliPay();
				break;
			default:
				showToast(quickPayMsg);
				updateGetDiscountStatus(FAIL);
				showInputMethod(discount_code_edittext, true);
				discount_code_edittext.setSelection(discount_code_edittext.getText().length());
				payButton.setEnabled(true);
				break;
			}
		}
	};
	
	Handler quickPayHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			pd.dismiss();

			Bundle data = msg.getData();
			String error = data.getString("Error");
			if (error != null && !error.isEmpty()) {
				showToast(error);
				quickPayButton.setEnabled(true);
				return;
			}
			int flag = FAIL;
			String val = data.getString("value");
			String quickPayMsg =null;
			try {
				JSONObject result = new JSONObject(val);
				boolean isSuccess = result.getBoolean("success");
				if (!isSuccess){
					quickPayMsg = result.getString("msg");
				}
				flag = isSuccess?SUCCESS:FAIL;
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				showToast(getResources().getString(R.string.T_NoNet_NoPreferential));
			} catch(Exception e){
				showToast(e.getMessage());
			}
			Intent intent = new Intent();
			switch (flag) {
			case SUCCESS:
				OrderDAO dao = new OrderDAO(PayActivity.this);
				orderInfo.setOrderStatus(Order.ORDER_STATUS_PAID);
				dao.updateOrderStatus(orderInfo);
				intent.setClass(PayActivity.this, PaySuccessActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("orderInfo", orderInfo);
				
				new Thread(orderCountRunnable).start();
				
				intent.putExtras(bundle);
				PayActivity.this.startActivity(intent);
				finish();
				break;
			default:
				updateGetDiscountStatus(FAIL);
				showToast(quickPayMsg);
				quickPayButton.setEnabled(true);
				break;
			}
		}
	};

	Handler preferentialHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			//			pd.dismiss();

			Bundle data = msg.getData();
			String error = data.getString("Error");
			if (error != null && !error.isEmpty()) {
				updateGetDiscountStatus(FAIL);
				showInputMethod(discount_code_edittext, true);
				discount_code_edittext.setSelection(discount_code_edittext.getText().length());
				showToast(error);
				return;
			}

			String val = data.getString("value");
			try {
				JSONObject result = new JSONObject(val);
				boolean isSuccess = result.getBoolean("success");
				if (isSuccess) {
					float price = (float) result.getDouble("price");
					updateGetDiscountStatus(SUCCESS);
					discount_num.setText("- "+price+ getResources().getString(R.string.T_Price_uint));
					DecimalFormat df = new DecimalFormat();
					df.setMaximumFractionDigits(2);
					total_fee_with_discount = Float.parseFloat(df.format(Float.parseFloat(total_fee)-price));
					
					if(total_fee_with_discount<=0){
						total_fee_with_discount = 0;
						payButton.setVisibility(View.GONE);
						quickPayButton.setVisibility(View.VISIBLE);
					}
					real_pay_num.setText(getResources().getString(R.string.RealNeedToPay)+total_fee_with_discount+ getResources().getString(R.string.T_Price_uint));
				} else {
					updateGetDiscountStatus(FAIL);
					showInputMethod(discount_code_edittext, true);
					discount_code_edittext.setSelection(discount_code_edittext.getText().length());
					Log.i("msg_code", result.toString());
					String rt = result.getString("msg");
					if(rt!=null || !"".equals(rt)){
						showToast(rt);
					}else{
						showToast(getResources().getString(R.string.CouponInvalid));
					}
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				showToast(getResources().getString(R.string.T_NoNet_NoPreferential));
			} catch(Exception e){
				showToast(e.getMessage());
			}
		}
	};
	
	Runnable getAlipayconfigsRunnable = new Runnable() {
		@Override
		public void run() {
			String url = ConfigProperties.getAlipayconfigsUrl();
			HttpClient httpclient = new DefaultHttpClient();
			HttpGet get = new HttpGet(url);
			UserHelper helper = new UserHelper();
			get.setHeader("username", helper.getUserName());
			get.setHeader("password", helper.getPassword());
			Message msg = new Message();
			Bundle data = new Bundle();
			try {
				HttpResponse response = httpclient.execute(get);
				HttpEntity resEntity = response.getEntity();
				
				if (resEntity != null) {
					
					String res = EntityUtils.toString(resEntity, Charset
							.forName("UTF-8").toString());
			
					JSONObject result;
					result = new JSONObject(res);
					String alipayconfigs = result.getString("alipayconfigs");
					byte[] dec =  Base64.decode(alipayconfigs, Base64.DEFAULT);
					
					String decontent = new String(decrypt(dec, password));
					result = new JSONObject(decontent.substring(1, decontent.length()-1));
					Keys.DEFAULT_PARTNER =result.getString("partner");
					Keys.DEFAULT_SELLER =result.getString("selleremail");
					Keys.PRIVATE =result.getString("privatekey");
					alipaynotifyurl = result.getString("alipaynotifyurl");
					resEntity.consumeContent();
				}else{
					data.putString("Error", getResources().getString(R.string.T_NoNet));
				}
			} catch (UnsupportedEncodingException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet));
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet));
				e.printStackTrace();
			} catch (IOException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet));
				e.printStackTrace();
			} catch (ParseException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet));
				e.printStackTrace();
			} catch (JSONException e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet));
				e.printStackTrace();
			} catch (Exception e) {
				data.putString("Error", getResources().getString(R.string.T_NoNet));
				e.printStackTrace();
			} finally {
				msg.setData(data);
				getAlipayconfigsHandler.sendMessage(msg);
				httpclient.getConnectionManager().shutdown();
			}
		}
	};
	
	Handler getAlipayconfigsHandler = new Handler() {
		@SuppressWarnings("deprecation")
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Bundle data = msg.getData();
			pd.dismiss();
			String error = data.getString("Error");
			if (error != null && !error.isEmpty()) {
				showToast(error);
				if (useCode){
					cancelCoupon();
				}
				payButton.setEnabled(true);
				return;
			}

			try {
		
				String info = getNewOrderInfo();
				String sign = Rsa.sign(info, Keys.PRIVATE);
				sign = URLEncoder.encode(sign);
				info += "&sign=\"" + sign + "\"&" + getSignType();

				final String orderInfo = info;
				new Thread() {
					public void run() {
						JHAlipay alipay = new JHAlipay(PayActivity.this,
								payHandler);

						// 设置为沙箱模式，不设置默认为线上环境
						// alipay.setSandBox(true);

						String result = alipay.pay(orderInfo);

						Message msg = new Message();
						msg.what = RQF_PAY;
						msg.obj = result;
						payHandler.sendMessage(msg);
					}
				}.start();

			} catch (Exception ex) {
				ex.printStackTrace();
				if (useCode){
					cancelCoupon();
				}else{
					showToast(getResources().getString(R.string.T_Pay_Fail));
				}
				
				payButton.setEnabled(true);
			}
		}
	};
	
	public byte[] decrypt(byte[] src, String password) throws Exception {  
		// DES算法要求有一个可信任的随机数源  
		SecureRandom random = new SecureRandom();  
		// 创建一个DESKeySpec对象  
		DESKeySpec desKey = new DESKeySpec(password.getBytes());  
		// 创建一个密匙工厂  
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");  
		// 将DESKeySpec对象转换成SecretKey对象  
		SecretKey securekey = keyFactory.generateSecret(desKey);  
		// Cipher对象实际完成解密操作  
		Cipher cipher = Cipher.getInstance("DES");  
		// 用密匙初始化Cipher对象  
		cipher.init(Cipher.DECRYPT_MODE, securekey, random);  
		// 真正开始解密操作  
		return cipher.doFinal(src);  
	}  
	
	Runnable orderCountRunnable = new Runnable() {
		@Override
		public void run() {
			String url = ConfigProperties.getOrderCountServerUrl();
			HttpPost httpPost = new HttpPost(url);
			UserHelper helper = new UserHelper();
			httpPost.setHeader("username", helper.getUserName());
			httpPost.setHeader("password", helper.getPassword());
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("orderid",orderCode));
			params.add(new BasicNameValuePair("orderprice",total_fee));
			if(!useCode){
				params.add(new BasicNameValuePair("payments",total_fee));
			}else{
				params.add(new BasicNameValuePair("payments",String.valueOf(total_fee_with_discount)));
			}
			params.add(new BasicNameValuePair("customername", orderInfo.getDeliveryInfo().getConsignee()));
			params.add(new BasicNameValuePair("customerphone", orderInfo.getDeliveryInfo().getMobile()));
			params.add(new BasicNameValuePair("customermail", orderInfo.getDeliveryInfo().getEmail()));
			params.add(new BasicNameValuePair("customeraddr", orderInfo.getDeliveryInfo().getAddress()));
			params.add(new BasicNameValuePair("appname",getResources().getString(R.string.app_name)));
			params.add(new BasicNameValuePair("appversion",getVersion()));
			params.add(new BasicNameValuePair("mobileos",orderInfo.getOs()));
			params.add(new BasicNameValuePair("createdtime",orderInfo.getCreatedtime()));
			
			params.add(new BasicNameValuePair("city", orderInfo.getDeliveryInfo().getCityCode()));
			params.add(new BasicNameValuePair("district", orderInfo.getDeliveryInfo().getCountyCode()));
			params.add(new BasicNameValuePair("zipcode", orderInfo.getDeliveryInfo().getPostCode()));
			params.add(new BasicNameValuePair("orderitemvos[0].productprice",
					String.valueOf(orderInfo.getPrice())));
			params.add(new BasicNameValuePair("products[0].productcount", orderInfo.getNumber()));
			
			
			if (orderInfo.getBookProject().getBook().getProduct().getCategory()==1){
				params.add(new BasicNameValuePair("products[0].producttype",
						"照片书"));
			}else{
				params.add(new BasicNameValuePair("products[0].producttype",
						"台历"));
			}
			
			params.add(new BasicNameValuePair("products[0].productname",
					orderInfo.getBookProject().getBook().getProduct().getName()));

			Message msg = new Message();
			Bundle data = new Bundle();
			try {
				httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
				
				BasicHttpParams httpParams = new BasicHttpParams();  
			    HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);  
			    HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);  
				HttpClient httpclient = new DefaultHttpClient(httpParams);
				HttpResponse httpResponse = httpclient.execute(httpPost);
				String result = EntityUtils.toString(httpResponse.getEntity());

				data.putString("value", result);
				msg.setData(data);
				orderCountHandler.sendMessage(msg);

			} catch (UnsupportedEncodingException e) {
				SendExceptionByEmail(e,null);
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				SendExceptionByEmail(e,null);
				e.printStackTrace();
			} catch (IOException e) {
				SendExceptionByEmail(e,null);
				e.printStackTrace();
			}catch (Exception e) {
				SendExceptionByEmail(e,null);
				e.printStackTrace();
			}
		}
	};
	
	Handler orderCountHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Bundle data = msg.getData();

			String val = data.getString("value");
			try {
				
				JSONObject result = new JSONObject(val);
				boolean isSuccess = result.getBoolean("success");
				if (!isSuccess) {
					SendExceptionByEmail(null,val);
				}

			} catch (JSONException e) {
				SendExceptionByEmail(null,val);
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	};
	
	/**
	 * 能过邮件发送错误信息
	 * @param ex
	 * @return
	 */
	private boolean SendExceptionByEmail(Throwable ex,String message)
	{

		String result= null;
		if (ex != null){
			Writer writer = new StringWriter();
			PrintWriter printWriter = new PrintWriter(writer);
			ex.printStackTrace(printWriter);
			Throwable cause = ex.getCause();
			while(cause != null)
			{
				cause.printStackTrace(printWriter);
				cause=cause.getCause();
			}
			printWriter.close();
			result= writer.toString();
		}else{
			result = message;
		}

		String subject="Android order count server error";
		
		//通过邮件发送信息
		AsyncTask<String, Integer, Boolean> sendTask= new AsyncTask<String, Integer, Boolean>(){
			@Override
			protected Boolean doInBackground(java.lang.String... content) {
				// TODO Auto-generated method stub
				try{
					//邮箱设置信息
					String errorEmail=ConfigProperties.getErrorMail();
					String receiveEmail=ConfigProperties.getErrorMailReciver();
					String pwd=ConfigProperties.getErrorMailPwd();
					String host=ConfigProperties.getMailHost();
					MailSenderInfo mailInfo=new MailSenderInfo();
					mailInfo.setMailServerHost(host);
					mailInfo.setMailServerPort("25");
					mailInfo.setValidate(true);
					mailInfo.setUserName(errorEmail);
					mailInfo.setPassword(pwd);
					mailInfo.setFromAddress(errorEmail);
					mailInfo.setToAddress(receiveEmail);
					mailInfo.setSubject(content[1]);
					mailInfo.setContent(content[0]);
					MailSendHelp sms = new MailSendHelp();   
			        boolean result=sms.sendTextMail(mailInfo);
			        return result;
					}
					catch(Exception e)
					{
						e.printStackTrace();
						return false;
					}				
			}			
			@Override
			protected void onPostExecute(Boolean result)
			{
				return;
			}	
		};
		//第一个参数是内容，第二个参数是subject
		sendTask.execute(result,subject);
		return true;
	}
	
	public String getVersion() {
		try {
		    PackageManager manager = this.getPackageManager();
		    PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
		    String version = info.versionName;
		    return version;
		} catch (Exception e) {
		    e.printStackTrace();
		    return "unknown";
		}
	}
	 
	protected void updateCodes() {
		for(int i = 0;i<capacity;i++){
			if(i<discount_code_edittext.getText().length()){
				codes.get(i).setText(discount_code_edittext.getText().toString().subSequence(i,i+1));
			}else{
				codes.get(i).setText("");
			}
		}
	}
	private void showInputMethod(EditText et,boolean flag){
		if(et!=null){
			et.setFocusable(flag);
			et.setFocusableInTouchMode(flag);
			if(flag)
				et.requestFocus();
			InputMethodManager inputManager =
					(InputMethodManager)et.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
			if(flag)
				inputManager.showSoftInput(et, 0);
			else
				inputManager.hideSoftInputFromWindow(et.getWindowToken(), 0);
		}
	}
	private void initCodes() {
		codes = new Vector<BorderTextView>(capacity);
		ApplicationInfo appInfo = getApplicationInfo();
		for(int i = 0; i<capacity;i++){
			int resID = getResources().getIdentifier( "code_num_"+i, "id", appInfo.packageName);
			codes.add((BorderTextView) findViewById(resID));
		}
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			showDialog();
		}
		return false;
	}

	private String getSignType() {
		return "sign_type=\"RSA\"";
	}

	private void showDialog() {

		final Dialog dialog = new Dialog(PayActivity.this, R.style.JHDialog);
		//设置它的ContentView
		dialog.setContentView(R.layout.dialog_general);
		Button buttonOK = (Button) dialog.findViewById(R.id.dialog_button_ok);
		Button buttonCancel = (Button) dialog.findViewById(R.id.dialog_button_cancel);
		TextView dialogTitle = (TextView) dialog.findViewById(R.id.dialog_title);
		TextView dialogMessage = (TextView) dialog.findViewById(R.id.dialog_message);

		buttonOK.setBackgroundResource(R.drawable.delete_style);
		buttonCancel.setBackgroundResource(R.drawable.grey_style);
		buttonOK.setText(R.string.T_Give_up_Config);
		buttonCancel.setText(R.string.T_Cancel);
		dialogTitle.setText(R.string.T_Order_Not_Pay);
		dialogMessage.setText(R.string.T_Give_Up_Pay);

		buttonOK.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			
				if(AccountDetailActivity.class.getName().equals(from)){
					finish();
					return; 
				}
				
				Intent intent = new Intent();
				/*if (orderInfo.getBookProject().getBook().getProduct().getCategory()==2){
					intent.putExtra("AblumHome", false);
				}*/
				intent.putExtra("FragmentIndex", 1);
				intent.setClass(PayActivity.this, HomeChangeActivity.class);
				PayActivity.this.startActivity(intent);
				finish();
			}
		});
		buttonCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

		dialog.show();
	}

	@SuppressWarnings("deprecation")
	private String getNewOrderInfo() {
		StringBuilder sb = new StringBuilder();
		sb.append("partner=\"");
		sb.append(Keys.DEFAULT_PARTNER);
		sb.append("\"&seller_id=\"");
		sb.append(Keys.DEFAULT_SELLER);
		sb.append("\"&out_trade_no=\"");
		sb.append(orderCode);
		sb.append("\"&subject=\"");
		sb.append(orderInfo.getBookProject().getBook().getProduct().getName());
		sb.append("\"&body=\"");
		sb.append(orderInfo.getBookProject().getBook().getProduct().getDescription());
		sb.append("\"&total_fee=\"");
		if(!useCode){
			sb.append(total_fee);
		}else{
			sb.append(total_fee_with_discount);
		}
		sb.append("\"&notify_url=\"");
		// 网址需要做URL编码
		sb.append(URLEncoder.encode(alipaynotifyurl));
		sb.append("\"&service=\"mobile.securitypay.pay");
		sb.append("\"&payment_type=\"1");
		sb.append("\"&_input_charset=\"UTF-8");
		sb.append("\"");
		return new String(sb);
	}

	Handler payHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			Result result = new Result((String) msg.obj);

			switch (msg.what) {
			case RQF_PAY:
				Intent intent = new Intent();
				if (result.isPaySuccess()) {
					new Thread(orderCountRunnable).start();
					OrderDAO dao = new OrderDAO(PayActivity.this);
					orderInfo.setOrderStatus(Order.ORDER_STATUS_PAID);
					dao.updateOrderStatus(orderInfo);
					intent.setClass(PayActivity.this, PaySuccessActivity.class);
				} else {
					if (result.isCanceled()) {
						payButton.setEnabled(true);
						if (useCode){
							cancelCoupon();
						}
						return;
					}
					
					if (useCode){
						cancelCoupon();
						return;
					}else{
						intent.setClass(PayActivity.this, PayFailedActivity.class);
					}
				}
				Bundle bundle = new Bundle();
				bundle.putSerializable("orderInfo", orderInfo);

				intent.putExtras(bundle);
				PayActivity.this.startActivity(intent);
				if (result.isPaySuccess()) {
					finish();
				}
				payButton.setEnabled(true);
				break;
			case RQF_LOGIN: 
				cancelCoupon();
				payButton.setEnabled(true);
				break;
			default:
				cancelCoupon();
				payButton.setEnabled(true);
				break;
			}
		};
	};
}
